import os;
import time
import utime
from machine import Pin
import network
import ntptime
from machine import RTC

p13 = Pin(13, Pin.OUT)    # led指示灯

def  wifi_init(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep(3);
    # if not wlan.isconnected():
    if 1:
        print('connecting to net<',ssid ,'>:<',password,'>')
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            time.sleep(1);
    print('network config:', wlan.ifconfig());

def get_timestamp():
	rtc = RTC()
	year, month, day, weekday, hour, minute, second, subsecond = rtc.datetime()
	rtc_time = utime.mktime(
	    (year+30, month, day, hour, minute, second, 0, 0))  # 年份使用2000+
	rtc_time -= 8*3600
	print('rtc_time=', rtc_time)
	return rtc_time
      
def ntp_sync_rtc():
	print("sync rtc form ntp")
	ntptime.host = 'time.nist.gov'
	ntptime.settime()
	tm = ntptime.time()  # 获取网络时间（从 1970 年 1 月 1 日开始的秒数）
	tm = tm + 8*3600  # 东8区
	year, month, day, hour, minute, second, _, _ = utime.localtime(tm)  # 转换为元组形式
	print("Network Time:", year, month, day, hour, minute, second)  # 输出结果
	rtc = RTC()  # 初始化 RTC
	rtc.datetime((year, month, day, 0, hour, minute, second, 0))  # 同步 RTC 时间
	get_timestamp()


#此文件cp到设备上以后重命名为main.py,micropython 就可以开机运行
if __name__ == '__main__':
	wifi_init('aaaoppo', '12345678')
	# wifi_init('MagicYang_01', '123454321')
	ntp_sync_rtc()



